<?php
class LetterInsController extends AppController {
    //var $pageTitle = 'Letter Ins';
    var $pageTitle = 'Rekap Nomor Surat Masuk';

    // property related to upload image
    var $pathPrefix;
    var $pathImage;
    var $fieldImage;
    var $errorUpload;
    var $resizedPrefix;
    var $thumbPrefix;

    function beforeFilter() {
        $this->pathPrefix  = WWW_ROOT . 'files' . DS . 'letter_in_photos';
        $this->pathImage = $this->pathPrefix . DS;
        $this->urlImage = $this->webroot . 'files/letter_in_photos/';
        $this->fieldImage = 'imagename';
        $this->resizedPrefix = 'thumb_';
        $this->thumbPrefix = 'thumbsmall_';
        parent::beforeFilter();
    }

    function index() {
        $this->paginate['order'] = array('LetterIn.created' => 'desc');
        parent::index();
    }

    function verify_list() {
        $this->paginate['order'] = array('LetterIn.created' => 'desc');

        $condition = array();

        // filter by field passed in tablegrid
        $str_fl = '';
        if ( isset($this->params['url']['search']) && $this->params['url']['search'] == 'Search' ) {
            App::import('Sanitize');
            $filtered_link   = array();
            $filtered_link[] = '?search=Search';

            foreach ( $this->params['url'] as $param => $value ) {
                if ( !empty($value) && $param != 'url' && $param != 'search' && $param != 'ref') {
                    $filtered_link[] = $param . "=" . $value;
                    $this->set($param . "Value", $value);
                    $like = str_replace('*', '%', Sanitize::paranoid($value, array('*', ' ', '-')));
                    $condition[$this->modelName.".$param LIKE"] = $like;
                }
            }

            if (!empty($filtered_link)) {
                $str_fl = implode("&", $filtered_link);
            }
        }

        $this->set('str_fl', $str_fl);
        $this->set('records', $this->paginate($condition));
        $this->set('formgrid', Helper::url('delete_rows'));
        $this->pageTitle = 'Verifikasi Surat Masuk';
    }

    function verify($id = null) {
        $this->__setAdditionals($id);
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect('verify_list');
        }
		$this->set('id', $id);

        if (!empty($this->data)) {
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("successcully edited", true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("cannot save this modification. Please fix the errors mentioned belows", true);

            $this->{$this->modelName}->id = $id;
            $saved = array(
                'validate' => false,
                'fieldList' => array(
                    'term_code_id', 'unit_code_id', 'cabinet_no', 'box_no', 'retention',
                    'filling_cabinet_no', 'filling_box_no', 'verified'
                )
            );
			if ($this->{$this->modelName}->save($this->data, $saved)) {
                if ( isset($this->data['LetterIn']['LetterInImage']['imagename']['name']) &&
                     !empty($this->data['LetterIn']['LetterInImage']['imagename']['name']) ) {
                    $imgname = $this->data['LetterIn']['LetterInImage']['imagename']['name'];
                    $tmps = $this->data['LetterIn']['LetterInImage']['imagename']['tmp_name'];
                    $errors = $this->data['LetterIn']['LetterInImage']['imagename']['error'];

                    foreach ($imgname as $key => $name) {
                        if ( ($s = $this->__handleUploadImage($errors[$key], $tmps[$key], $name)) !== FALSE ) {
                            $saved_img = array(
                                'imagename' => $s, 'letter_in_id' => $this->LetterIn->id
                            );
                            $this->LetterIn->LetterInImage->create();
                            $this->LetterIn->LetterInImage->save($saved_img);
                        }
                    }
                }

				$this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect('verify_list');
			} else {
                $this->Session->setFlash($messageFlashError, 'error');
            }
		}

		if (empty($this->data)) {
			$this->data = $this->{$this->modelName}->find('first', array(
                'conditions' => array($this->modelName . '.id' => $id),
            ));

            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect('verify_list');
            }
		} else {
            $this->data[$this->modelName]['id'] = $id;
        }
        $this->set('letter', $this->data);
    }

    function add() {
        $this->__setAdditionals();
        $this->__saving();
    }

    function edit($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect();
        }

		$this->set('id', $id);
        $this->__setAdditionals($id);
        $this->__saving($id);

		if (empty($this->data)) {
			$this->data = $this->{$this->modelName}->find('first', array(
                'conditions' => array($this->modelName . '.id' => $id)
            ));

            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect('index');
            }
		} else {
            $this->data[$this->modelName]['id'] = $id;
        }
    }

    function delImage($id, $letter_in_id) {
        $action = 'edit';
        if ( isset($this->params['url']['verify']) ) {
            $action = 'verify_list';
            $letter_in_id = '';
        }
        $this->Session->setFlash('Gambar tidak berhasil terhapus', 'error');

        $this->LetterIn->LetterInImage->id = $id;
        $imagename = $this->LetterIn->LetterInImage->field($this->fieldImage);

        if ( $this->LetterIn->LetterInImage->del($id) ) {
            @unlink($this->pathPrefix . DS . $imagename);
            @unlink($this->pathPrefix . DS . $this->resizedPrefix . $imagename);
            @unlink($this->pathPrefix . DS . $this->thumbPrefix . $imagename);
            $this->Session->setFlash('Gambar berhasil terhapus', 'success');
        }
        $this->redirect(array('action' => $action, $letter_in_id));
    }

    function __handleUploadImage($error_code, $tmp_name, $image_name) {
        $error = array();
        $possible_errors = array(
            1 => 'php.ini max file exceeded',
            2 => 'html form max file size exceeded',
            3 => 'file upload was only partial',
            4 => 'no file was attached'
        );

        // check for PHP's built-in uploading errors
        if ( $error_code > 0 ) {
            $error[] = $possible_errors[$error_code];
        }

        // check that the file we're working on really was the subject of an HTTP upload
        if ( !@is_uploaded_file($tmp_name) ) {
            $error[] = 'Not an HTTP upload';
        }

        // check if uploaded file is in fact an image
        if ( !@getimagesize($tmp_name) ) {
            $error[] = 'Only image uploads are allowed';
        }

        // check if our target directory is writeable
        if ( !is_writable($this->pathImage) ) {
            $error[] = 'Target upload is not writeable.';
        }

        if ( empty($error) ) {
            // Make a unique filename for the uploaded files and check it is not already
            // taken.

            // first check if we could use the original image name
            $image_path = $this->pathImage . $image_name;
            if ( file_exists($image_path) ) {
                $image_name = time() . '_' . $image_name;

                // uses time and iterate until it found unique name
                $image_path = $this->pathImage . $image_name;
                if ( file_exists($image_path) ) {
                    $counter = 1;
                    while ( file_exists($image_path = $this->pathImage . $counter . '_' . $image_name ) ) {
                        $counter++;
                    }
                    $image_name = $counter . '_' . $image_name;
                }
            }

            // error moving uploaded file
            if ( !@move_uploaded_file($tmp_name, $image_path) ) {
                $this->data['LetterIn'][$this->fieldImage] = '';
                $this->errorUpload = 'Receiving directory insufficient permission';

                return false;
            }

            // resizing
            $this->__resizeImage($image_name);

            return $image_name;
        } else {
            $this->errorUpload = $error;
            return false;
        }
    }

    function __setAdditionals($id = null) {
        $unit_codes = $this->LetterIn->UnitCode->find('list', array(
            'order' => array('UnitCode.name ASC')
        ));
        $terms = $this->LetterIn->TermCode->find('all', array(
            'order' => array('TermCode.code ASC')
        ));
        $term_codes = $substantif = $fasilitatif = array();
        foreach ($terms as $term) {
            $term_codes[$term['TermCode']['id']] = '(' . $term['TermCode']['code'] . ') ' . $term['TermCode']['name'];
            switch ($term['TermCode']['category']) {
                case 'Substantif':
                    $substantif[$term['TermCode']['id']]  = '(' . $term['TermCode']['code'] . ') ' . $term['TermCode']['name'];
                    break;
                case 'Fasilitatif':
                    $fasilitatif[$term['TermCode']['id']] = '(' . $term['TermCode']['code'] . ') ' . $term['TermCode']['name'];
                    break;
            }
        }
        $this->set('substantif', json_encode($substantif));
        $this->set('fasilitatif', json_encode($fasilitatif));

        $this->set('unit_codes', $unit_codes);
        $this->set('term_codes', $term_codes);

        if ( $id ) {
            $this->LetterIn->Behaviors->attach('Containable');
            $letter_in = $this->LetterIn->find('first', array(
                'conditions' => array(
                    'LetterIn.id' => $id
                ),
                'contain' => array(
                    'LetterInImage'
                )
            ));
            $this->set('letter_in', $letter_in);
        }

        // images related
        $this->set('fieldImage', $this->fieldImage);
        $this->set('urlImage', $this->urlImage);
        $this->set('resizedPrefix', $this->resizedPrefix);
        $this->set('thumbPrefix', $this->thumbPrefix);

        // set ajax URL
        $this->set('urlController', $this->__pathToController());
    }

    function __saving($id = null) {
        if ( !empty($this->data) ) {
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __('successfully added', true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' .
                __('cannot add this new record. Please fix the errors mentioned belows', true);
            if ( $id ) {
                $messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("successcully edited", true);
                $messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' .
                    __("cannot save this modification. Please fix the errors mentioned belows", true);
            }

            if ( $id ) {
                $this->LetterIn->id = $id;
            } else {
                $this->LetterIn->create();
            }
            $letter_ins = $this->data;

			if ( $this->LetterIn->save($this->data) ) {
                if ( isset($this->data['LetterIn']['LetterInImage']['imagename']['name']) &&
                     !empty($this->data['LetterIn']['LetterInImage']['imagename']['name']) ) {
                    $imgname = $this->data['LetterIn']['LetterInImage']['imagename']['name'];
                    $tmps = $this->data['LetterIn']['LetterInImage']['imagename']['tmp_name'];
                    $errors = $this->data['LetterIn']['LetterInImage']['imagename']['error'];

                    foreach ($imgname as $key => $name) {
                        if ( ($s = $this->__handleUploadImage($errors[$key], $tmps[$key], $name)) !== FALSE ) {
                            $saved_img = array(
                                'imagename' => $s, 'letter_in_id' => $this->LetterIn->id
                            );
                            $this->LetterIn->LetterInImage->create();
                            $this->LetterIn->LetterInImage->save($saved_img);
                        }
                    }
                }
                $this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->redirect(array('action' => 'edit', $this->LetterIn->id));
			} else {
                $this->set('letter_ins', $letter_ins['LetterIn']);
                $this->Session->setFlash($messageFlashError, 'error');
			}
		}
    }
}
?>
